r"""
给定一个二叉树，检查它是否是镜像对称的。
例如，二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / \
  2   2
 / \ / \
3  4 4  3
 

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3

作者：力扣 (LeetCode)
链接：https://leetcode-cn.com/leetbook/read/data-structure-binary-tree/xoxzgv/
来源：力扣（LeetCode）
著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
"""
from collections import deque


class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if not root:
            return True
        queue = deque()
        queue.append(root)
        while queue:
            size = len(queue)
            res = []
            for i in range(size):
                cur = queue.popleft()
                if cur is None:
                    res.append(None)
                else:
                    res.append(cur.val)
                    queue.append(cur.left)
                    queue.append(cur.right)
            n = len(res)
            if n == 1:
                continue
            for i in range(n // 2):
                if res[i] != res[-(i + 1)]:
                    return False
        return True

    def is_symmetric(self, root: TreeNode) -> bool:
        def recur(left: TreeNode, right: TreeNode):
            if not left and not right:
                return True
            if not left or not right or left.val != right.val:
                return False
            return recur(left.left, right.right) and recur(left.right, right.left)
        return recur(root.left, root.right) if root else True


if __name__ == '__main__':
    tree = TreeNode(1)
    tree.left = TreeNode(2)
    tree.right = TreeNode(2)
    tree.left.left = TreeNode(3)
    tree.left.right = TreeNode(4)
    tree.right.left = TreeNode(4)
    tree.right.right = TreeNode(3)
    tree1 = TreeNode(1)
    tree1.left = TreeNode(2)
    tree1.right = TreeNode(2)
    tree1.left.right = TreeNode(3)
    tree1.right.right = TreeNode(3)
    s = Solution()
    print(s.isSymmetric(tree))
    print(s.isSymmetric(tree1))
    print(s.is_symmetric(tree))
    print(s.is_symmetric(tree1))
